import 'dart:async';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wifi_info_flutter/wifi_info_flutter.dart';

final wifiNameProvider = StreamProvider<String?>((ref) {
  final wifiInfo = WifiInfo();
  final connectivity = Connectivity();
  final controller = StreamController<String?>();
  String? currentName;
  String? lastEmittedName;

  bool permissionDeniedNotified = false;

  Future<bool> ensurePermission() async {
    if (!(Platform.isIOS || Platform.isAndroid)) {
      return true;
    }

    PermissionStatus status = Platform.isIOS
        ? await Permission.locationWhenInUse.status
        : await Permission.location.status;

    if (status.isGranted || status.isLimited) {
      permissionDeniedNotified = false;
      return true;
    }

    if (!permissionDeniedNotified) {
      status = Platform.isIOS
          ? await Permission.locationWhenInUse.request()
          : await Permission.location.request();

      if (status.isGranted || status.isLimited) {
        permissionDeniedNotified = false;
        return true;
      }

      if (status.isPermanentlyDenied) {
        permissionDeniedNotified = true;
        controller.addError(const WifiPermissionException());
        return false;
      }

      if (status.isDenied && Platform.isAndroid) {
        // Android可能需要再次确认通用location权限
        final fallbackStatus = await Permission.location.status;
        if (fallbackStatus.isGranted) {
          permissionDeniedNotified = false;
          return true;
        }
        if (!fallbackStatus.isPermanentlyDenied) {
          final requested = await Permission.location.request();
          if (requested.isGranted) {
            permissionDeniedNotified = false;
            return true;
          }
          if (requested.isPermanentlyDenied) {
            permissionDeniedNotified = true;
            controller.addError(const WifiPermissionException());
            return false;
          }
        } else {
          permissionDeniedNotified = true;
          controller.addError(const WifiPermissionException());
          return false;
        }
      }

      permissionDeniedNotified = true;
      controller.addError(const WifiPermissionException());
      return false;
    }

    if (status.isPermanentlyDenied) {
      permissionDeniedNotified = true;
      controller.addError(const WifiPermissionException());
      return false;
    }

    if (!permissionDeniedNotified) {
      permissionDeniedNotified = true;
      controller.addError(const WifiPermissionException());
    }
    return false;
  }

  Future<void> init() async {
    final hasPermission = await ensurePermission();
    if (!hasPermission) {
      controller.add(null);
      return;
    }
    currentName = await wifiInfo.getWifiName();
    lastEmittedName = _sanitizeWifiName(currentName);
    controller.add(lastEmittedName);
  }

  // 轮询计时器（每3秒检查一次）
  Timer? pollingTimer;

  // 轮询检查函数
  Future<void> checkWifiChange() async {
    try {
      final hasPermission = await ensurePermission();
      if (!hasPermission) {
        controller.add(null);
        return;
      }
      final newName = await wifiInfo.getWifiName();
      if (newName != currentName) {
        currentName = newName;
        final sanitized = _sanitizeWifiName(currentName);
        if (sanitized != lastEmittedName) {
          lastEmittedName = sanitized;
          controller.add(lastEmittedName);
        }
      }
    } catch (e) {
      // 忽略轮询错误，继续下一次检查
    }
  }

  // 启动
  init();

  // 启动轮询
  pollingTimer = Timer.periodic(const Duration(seconds: 3), (_) async {
    await checkWifiChange();
  });

  // 网络类型变化监听
  final subscription = connectivity.onConnectivityChanged.listen((
    result,
  ) async {
    final hasPermission = await ensurePermission();
    if (!hasPermission) {
      controller.add(null);
      return;
    }

    if (result.contains(ConnectivityResult.wifi)) {
      final name = await wifiInfo.getWifiName();
      final sanitizedName = _sanitizeWifiName(name);
      if (sanitizedName != lastEmittedName) {
        lastEmittedName = sanitizedName;
        controller.add(sanitizedName);
      }
    } else {
      lastEmittedName = null;
      controller.add(null);
    }
  });

  // 清理资源
  ref.onDispose(() {
    pollingTimer?.cancel();
    subscription.cancel();
    controller.close();
  });

  return controller.stream;
});

String? _sanitizeWifiName(String? name) {
  if (name == null) return null;
  if (name.isEmpty) return null;
  if (name == '<unknown ssid>') return null;
  if (name == 'null') return null;
  return name;
}

class WifiPermissionException implements Exception {
  const WifiPermissionException();
}
